#include "IGrid.h"
#include "ICell.h"

IGrid::IGrid(CCSize size)
	: m_size(size), m_isDirty(false)
{
	for (int i = 0; i < m_size.width * m_size.height; i++)
	{
		m_cellVector[i] = NULL;

	}
}

IGrid::~IGrid(void)
{
}

ICell* IGrid::GetCell(CCPoint p)
{
	int index = CCPoint2Index(p);
	if (index < 0 || index >= m_size.width * m_size.height)
		return NULL;
	return m_cellVector[index];
}

void IGrid::RemoveCell(CCPoint p)
{
	int index = CCPoint2Index(p);
	if (index < 0 || index >= m_size.width * m_size.height)
		return;
	// should not be deleted when using flyweight model
	//if (m_cellVector[index] != NULL)
	//	delete m_cellVector[index];
	m_cellVector[index] = NULL;
	SetDirty();
}

void IGrid::ReplaceCell(CCPoint p, unsigned int cellType)
{
	int index = CCPoint2Index(p);
	if (index < 0 || index >= m_size.width * m_size.height)
		return;
	if (m_cellVector[index] != NULL)
		delete m_cellVector[index];
	m_cellVector[index] = CellFactory::sharedCellFactory()->GetCell(cellType);
	SetDirty();
}

void IGrid::SwapCell(CCPoint from, CCPoint to)
{
	int indexTo = CCPoint2Index(to);
	if (indexTo < 0 || indexTo >= m_size.width * m_size.height)
		return;

	int indexFrom = CCPoint2Index(from);
	if (indexFrom < 0 || indexFrom >= m_size.width * m_size.height)
		return;


	ICell* cell = m_cellVector[indexTo];
	m_cellVector[indexTo] = m_cellVector[indexFrom];
	m_cellVector[indexFrom] = cell;
	SetDirty();
}

//bool IGrid::LoadLevel()
//{
//	return true;
//}

int IGrid::CCPoint2Index(CCPoint p)
{
	int index = int(p.y * m_size.width + p.x);
	if (index < 0 || index > m_size.width * m_size.height)
		return -1;
	return index;
}

bool IGrid::IsDirty()
{
	return m_isDirty;
}

void IGrid::CleanDirty()
{
	m_isDirty = false;
}